import logging
from fastmcp import Client
from config.mcp_config.mcp.mcp import a12306config

# 导入mcp装饰器
from mcp_server import mcp

logger = logging.getLogger('12306')

# 初始化客户端
client = Client(a12306config)

@mcp.tool()
async def query_tickets(date: str, from_station: str, to_station: str, train_type: str = ""):
    """
    查询12306余票信息
    
    Args: 
        date (str): 出发日期，格式为 "yyyy-MM-dd"
        from_station (str): 出发站ID
        to_station (str): 到达站ID
        train_type (str): 车次类型筛选，可选值：G(高铁/城际),D(动车),Z(直达特快),T(特快),K(快速),O(其他),F(复兴号),S(智能动车组)
    
    Returns:
        dict: 余票信息
    """
    try:
        async with client:
            # 调用远程工具
            response = await client.call_tool(
                "get-tickets",
                {
                    "date": date,
                    "fromStation": from_station,
                    "toStation": to_station,
                    "trainFilterFlags": train_type
                }
            )
            
            result = response.content[0].text
            # 检查返回结果是否包含错误信息
            if "Error:" in result or "Station not found" in result:
                logger.info(f"查询余票失败: {result}")
                return {"success": False, "result": result}
            logger.info(f"查询余票成功: {result}")
            return {"success": True, "result": result}
            
    except Exception as e:
        error_msg = f"调用失败：{str(e)}"
        logger.error(error_msg)
        return {"success": False, "result": error_msg}

@mcp.tool()
async def get_station_code(city: str) -> dict:
    """
    通过中文城市名查询代表该城市的station_code
    
    Args:
        city (str): 城市名称
    
    Returns:
        dict: 车站代码信息
    """
    try:
        async with client:
            # 调用远程工具获取车站代码
            response = await client.call_tool(
                "get-station-code-of-citys",
                {
                    "citys": city
                }
            )
            
            result = response.content[0].text
            logger.info(f"获取车站代码成功: {result}")
            return {"success": True, "result": result}
            
    except Exception as e:
        error_msg = f"调用失败：{str(e)}"
        logger.error(error_msg)
        return {"success": False, "result": error_msg}

@mcp.tool()
async def get_current_date() -> dict:
    """获取当前日期，以上海时区（Asia/Shanghai, UTC+8）为准，返回格式为 "yyyy-MM-dd"。主要用于解析用户提到的相对日期（如"明天"、"下周三"），为其他需要日期的接口提供准确的日期输入。"""
    try:
        async with client:
            # 使用get-current-date工具获取当前日期
            date_response = await client.call_tool("get-current-date", {})
            result = date_response.content[0].text
            logger.info(f"当前日期：{result}")
            
            return {"success": True, "result": result}
            
    except Exception as e:
        error_msg = f"调用失败：{str(e)}"
        logger.error(error_msg)
        return {"success": False, "result": error_msg}